package org.asiainfo.system.service.impl;

import org.asiainfo.common.core.constant.CacheNames;
import org.asiainfo.common.core.constant.UserConstants;
import org.asiainfo.common.core.exception.ServiceException;
import org.asiainfo.common.core.utils.StringUtils;
import org.asiainfo.common.mybatis.stream.core.page.TableDataInfo;
import org.asiainfo.common.mybatis.stream.core.page.PageQuery;
import org.asiainfo.common.redis.utils.CacheUtils;
import org.asiainfo.system.domain.vo.SysConfigVo;
import org.asiainfo.system.domain.bo.SysConfigBo;
import org.asiainfo.system.domain.SysConfig;
import org.asiainfo.system.service.SysConfigService;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.asiainfo.common.core.utils.MapstructUtils;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.asiainfo.system.mapper.SysConfigMapper;
import com.mybatisflex.core.paginate.Page;

import java.util.Map;
import java.util.Collection;
import java.util.List;

/**
 * 参数配置表(SysConfig)表服务实现类
 *
 * @author dotor-ww
 * @since 2024-01-15 21:17:36
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    /**
     * 创建查询条件
     *
     * @param sysConfigBo 筛选条件
     * @return 查询结果
     */
    private QueryWrapper buildQueryWrapper(SysConfigBo sysConfigBo) {
        Map<String, Object> params = sysConfigBo.getParams();
        QueryWrapper query = query();
        query.like(SysConfig::getConfigName, sysConfigBo.getConfigName(), StringUtils.isNotBlank(sysConfigBo.getConfigName()));
        query.eq(SysConfig::getConfigType, sysConfigBo.getConfigType(), StringUtils.isNotBlank(sysConfigBo.getConfigType()));
        query.like(SysConfig::getConfigKey, sysConfigBo.getConfigKey(), StringUtils.isNotBlank(sysConfigBo.getConfigKey()));
        query.between(SysConfig::getCreateTime, params.get("beginTime"), params.get("endTime"),
            ObjectUtil.isNotNull(params.get("beginTime")) && ObjectUtil.isNotNull(params.get("endTime")));
        return query;
    }

    /**
     * 查询
     *
     * @param sysConfigBo 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SysConfigVo> queryList(SysConfigBo sysConfigBo) {
        QueryWrapper query = buildQueryWrapper(sysConfigBo);
        return listAs(query, SysConfigVo.class);
    }

    /**
     * 通过configId查询单条数据
     *
     * @param configId 主键
     * @return 实例对象
     */
    @Override
    public SysConfigVo queryById(Long configId) {
        return getOneAs(query().eq(SysConfig::getConfigId, configId), SysConfigVo.class);
    }

    /**
     * 分页查询
     *
     * @param sysConfigBo 筛选条件
     * @param pageQuery   分页对象
     * @return 查询结果
     */
    @Override
    public TableDataInfo<SysConfigVo> queryPageList(SysConfigBo sysConfigBo, PageQuery pageQuery) {
        QueryWrapper query = buildQueryWrapper(sysConfigBo);
        pageQuery.buildOrder(query);
        if (StringUtils.isBlank(pageQuery.getOrderBy())) {
            query.orderBy(SysConfig::getConfigId);
        }
        Page<SysConfigVo> page = pageAs(pageQuery.buildPage(), query, SysConfigVo.class);
        return TableDataInfo.build(page);
    }

    /**
     * 新增数据
     *
     * @param sysConfigBo 实例对象
     * @return 实例对象
     */
    @CachePut(cacheNames = CacheNames.SYS_CONFIG, key = "#sysConfigBo.configKey")
    @Override
    public String insertByBo(SysConfigBo sysConfigBo) {
        SysConfig sysConfig = MapstructUtils.convert(sysConfigBo, SysConfig.class);
        if (save(sysConfig)) {
            return sysConfig.getConfigValue();
        }
        throw new ServiceException("新增数据失败");
    }

    /**
     * 修改数据
     *
     * @param sysConfigBo 实例对象
     * @return 实例对象
     */
    @CachePut(cacheNames = CacheNames.SYS_CONFIG, key = "#sysConfigBo.configKey")
    @Override
    public String updateByBo(SysConfigBo sysConfigBo) {
        boolean update = false;
        SysConfig sysConfig = MapstructUtils.convert(sysConfigBo, SysConfig.class);
        if (ObjectUtil.isNotNull(sysConfig)) {
            if (ObjectUtil.isNotEmpty(sysConfig.getConfigId())) {
                SysConfig tempSysConfig = getById(sysConfig.getConfigId());
                if (!StringUtils.equals(tempSysConfig.getConfigKey(), sysConfig.getConfigKey())) {
                    CacheUtils.evict(CacheNames.SYS_CONFIG, tempSysConfig.getConfigKey());
                }
                update = updateById(sysConfig);
            } else {
                update = update(sysConfig, query().eq(SysConfig::getConfigKey, sysConfig.getConfigKey()));
            }
        }
        if (update) {
            return sysConfig.getConfigValue();
        }
        throw new ServiceException("操作失败!");
    }

    /**
     * 通过主键删除数据
     *
     * @param configIds 主键
     * @return 是否成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> configIds) {
        for (Long configId : configIds) {
            SysConfig sysConfig = getById(configId);
            if (ObjectUtil.isNotNull(sysConfig)) {
                if (StringUtils.equals(UserConstants.YES, sysConfig.getConfigType())) {
                    throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", sysConfig.getConfigKey()));
                }
                CacheUtils.evict(CacheNames.SYS_CONFIG, sysConfig.getConfigKey());
            }
        }
        return removeByIds(configIds);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        CacheUtils.clear(CacheNames.SYS_CONFIG);
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param sysConfigBo 参数配置信息
     * @return 结果
     */
    @Override
    public Boolean checkConfigKeyUnique(SysConfigBo sysConfigBo) {
        long configId = ObjectUtil.isNull(sysConfigBo.getConfigId()) ? -1L : sysConfigBo.getConfigId();
        SysConfig sysConfig = getOne(query().eq(SysConfig::getConfigKey, sysConfigBo.getConfigKey()));
        return !ObjectUtil.isNotNull(sysConfig) || sysConfig.getConfigId() == configId;
    }

    /**
     * 根据key查询配置
     *
     * @param configKey 参数key
     * @return 查询结果
     */
    @Cacheable(cacheNames = CacheNames.SYS_CONFIG, key = "#configKey")
    @Override
    public String selectConfigByKey(String configKey) {
        SysConfig retConfig = getOne(query().eq(SysConfig::getConfigKey, configKey));
        if (ObjectUtil.isNotNull(retConfig)) {
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }
}
